<script setup>
import {ref, onMounted, watch} from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
    data: {
        type: Object,
        required: true
    }
})

let chart = null
const target = ref()

onMounted(() => {
    chart = echarts.init(target.value);
    renderChart()
})

watch(() => props.data, () => {
    renderChart()
})
const renderChart = () => {
    const xData = props.data.map((item) => item.name);
    const yData = props.data.map((item) => item.value);
    /** @type EChartsOption */
    const option = {
        title: {
            text: '横向柱形图',
            textStyle: {
                color: '#FFFFFF',
                fontSize: 16
            }
        },
        xAxis: {
            show: false,
            type: 'value',
            max:  (value) =>(parseInt(value.max * 1.2))
        },
        yAxis: {
            type: 'category',
            data: xData,
            inverse: true,
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#FFFFFF'
            }
        },
        grid: {
            top: '15%',
            right: '10%',
            bottom: 0,
            left: 0,
            containLabel: true,
        },
        series: [
            {
                type: 'bar',
                data: yData,
                showBackground: true,
                backgroundStyle: {
                    color: '#03385a',
                    borderRadius: 5,
                },
                itemStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 1,
                        y2: 0,
                        colorStops: [{
                            offset: 0, color: '#05375a' // 100% 处的颜色
                        }, {
                            offset: 1, color: '#00a6f5' // 0% 处的颜色
                        }],
                    },
                    borderRadius: 5,
                },
                barWidth: 14,
                label: {
                    show: true,
                    position: [330, 0],
                    color: '#fff',
                },
            }
        ]
    };
    chart.setOption(option);
}
</script>

<template>
    <div>
        <div ref="target" class="w-full h-full"></div>
    </div>
</template>

<style scoped></style>
